package cn.smbms.service.impl;

import cn.smbms.dao.ProductDao;
import cn.smbms.entity.Product;
import cn.smbms.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductDao productDao;
    @Override
    public void addNewProduct(Product product) {
        productDao.save(product);
//        throw new RuntimeException("测试异常状态下事务是否回滚");
    }

    public List<Product> getAll(){
        return productDao.findAllProduct();
    }

    @Override
    public List<Product> getProductByName(String prductName,int id) {
        return productDao.findProductNames(prductName,id);
    }


    @Override
    public Product getProductById(int id) {
        return productDao.findProductId(id);
    }

    @Override
    public void updateProduct(Product product) {
        productDao.updateProduct(product.getProductId(),product.getProductName());
    }

    @Override
    public List<Product> getProductBySql() {
        return productDao.findSql();
    }

    @Override
    public Product getProductByNameAndId(int id, String name) {
        return productDao.findProductByProductIdAndProductName(id,name);
    }

    @Override
    public List<Product> getProductByIds(int... ids) {
        return productDao.findAllByProductIdIn(ids);
    }

    @Override
    public Page<Product> getProductByPages(int pageNo, int pageSize,
                                           String name) {
//        Specification<Product> specification = new Specification<Product>() {
//            @Override
//            public Predicate toPredicate(Root<Product> root,
//                                         CriteriaQuery<?> cq,
//                                         CriteriaBuilder cb) {
//                //like? 没有使用concat()函数
//                return cb.like(root.get("productName").as(String.class),name);
//            }
//        };
        PageRequest pageRequest = PageRequest.of((pageNo - 1) * pageSize, pageSize);
        Page<Product> all = productDao.findAll(
                (root,cq,cb)->cb.like(root.get("productName").as(String.class),name),
                pageRequest);
        return all;
    }
}
